package cn.bdqn.servlet;

import cn.bdqn.bean.User;
import cn.bdqn.service.UserService;
import cn.bdqn.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.setCharacterEncoding("UTF-8");
        String userName=request.getParameter("userName");
        String pwd=request.getParameter("pwd");
        //访问service层，
        UserService userService=new UserServiceImpl();
        User user=userService.login(userName,pwd);
        //获取session
        HttpSession session=request.getSession();
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();

        if(null!=user){
            session.setMaxInactiveInterval(60*2);
            session.setAttribute("user",user);
            //request.setAttribute("name",userName);
            //response.sendRedirect("newspages/admin.jsp");
            //out.print("登录成功");
            out.print(true);
            //转发
            //request.getRequestDispatcher("welcome.jsp").forward(request,response);
        }else{
            //重定向
            //response.sendRedirect("index.jsp");
            out.print(false);
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
